<?php
namespace common\helps;

/*
 * 自定义全局公共方法
 */

use backend\models\SysMessageTemplate;
use Yii;
use common\helps;
use PHPExcel;
use common\models\GoodsKeyword;
use backend\models\AuthAccess;
use backend\models\UserMappedRole;
use backend\models\AuthRule;
use yii\helpers\Url;
use backend\models\SysSeq;


class tools{

    /**
     * @param $pwd
     * @return string
     * 进行MD5加密
     */
    public static function md5pwd($pwd){
        $prefixPassword =Yii::$app->params['prefixPassword'];

        return md5($prefixPassword . $pwd);
    }

    /**
     * 取得当前SESSION_ID
     */
    public static function getSessionID(){
        if(!isset($_SESSION)){
            session_start();
        }
        return session_id();
    }

    /**
     * @return bool
     * 判断当前客户端是否已登录状态
     */
    public static function isloggedin(){
        $redis = new helps\redisHelper();
        if(!$redis->isloggedin()){
            return false;
        }
        return true;
    }

    /**
     * @return mixed
     * 取得已登录用户信息
     */
    public static function getloginUserInfo(){
        $redis = new helps\redisHelper();
        return  $redis->getloginUserInfo();
    }

    /**
     * @return mixed
     * 取得已登录会员信息
     */
    public static function getloginMasterInfo(){
        $redis = new helps\redisHelper();
        return  $redis->getLoginMasterInfo();
    }

    /**
     * @return bool
     * 判断当前客户端是否已登录状态
     */
    public static function isLogin(){
        $redis = new helps\redisHelper();
        if(!$redis->isLogin()){
            return false;
        }
        return true;
    }

    /**
     * @return array
     * 获取树形结构数据
     */
    public static function getCustomerTree($arr,$pid,$step){
        global $tree;
        foreach($arr as $key=>$val) {
            if($val['parent_id'] == $pid) {
                $flg = str_repeat('└─',$step);
                $val['html'] = $flg.$val['html'];
                $tree[] = $val;
                self::getCustomerTree($arr , $val['id'] ,$step+1);
            }
        }
        return $tree;
    }

	/**
	 * @author add by huangzhao 20170906 发送验证码
	 * @param  mod by FDG367 2018/04/16 587 【PC/WAP】会员注册成功后，发送短信。 start
	 * @param $mobiles 目标手机号
	 * @param $mobile_code 发送的条件 可以为空  目前一条断线只支持一个参数变量替换
	 * @param string $templateKey 模板名称 sms_crcode
	 * @return bool
	 */
    public static function sendMobileCode($mobiles,$mobile_code='',$templateKey='sms_crcode'){
        $sms = new api_sms_dianke();
        //mod by allen.qiang 20171011 改用消息模板数据 start

		//支持多个参数
		$smsCode	=[];

		if($smsCodeModuel	= SysMessageTemplate::$template[$templateKey]){
			foreach($smsCodeModuel as $key=>$val){
				$smsCode["$val"]	= $mobile_code;
			}
		}

		//替换发送的内容
        $content =  self::getMessageTemplate($templateKey,SysMessageTemplate::TYPE_ONE , $smsCode);

        //mod by allen.qiang 20171011 改用消息模板数据 end
        $result = $sms->sendSms($mobiles,$content);
        return $result;
    }


    /**
     * add by huangzhao 20170906
     * 生成随机数
     */
    public static function roundCode($length=6){
        $str='1234567890';

        $randStr = str_shuffle($str);//打乱字符串

        $code= substr($randStr,0,$length);//substr(string,start,length);返回字符串的一部分

        return $code;
    }

    //验证手机号
    public static function checkMobile($mobile){
       $is_check = preg_match('/^0?(13|14|15|17|18)[0-9]{9}$/', $mobile, $matches);
       return $is_check;
    }

    //手机号验证码关联存入redis
    public static function setSmsCode($mobile,$code){
        $redis = new helps\redisHelper();
        $redis->setSmsCode($mobile,$code);
    }

    //登录用户信息存入redis
    public static function setMasterInfo($data){
        $redis = new helps\redisHelper();
        $redis->setMasterInfo($data);
    }

    //读取用户的角色名称
    //add by allen.qiang 20170927
    public static function getUserRoleName($user_id){

        $post = Yii::$app->db->createCommand('SELECT role_id FROM `j_user_mapped_role` WHERE user_id = :user_id')
            ->bindValue(':user_id', $user_id)
            ->queryOne();
        if(!$post){
            return '';
        }
        $roles = $post['role_id'];

        $roles_info = Yii::$app->db->createCommand('SELECT role_name FROM j_user_role WHERE id IN (' .$roles .')')
            ->queryAll();

        if(!$roles_info){
            return '';
        }
        $roles_name = '';
        foreach($roles_info as $value){
            $roles_name = $roles_name . $value['role_name'] . ' ';
        }
        return $roles_name;
    }

    /**
     * @param $mobile
     * @param $content
     * 发送短信
     */
    public static function sendSms($mobile , $content){
        $smsObj = new api_sms_dianke();
        $smsObj->sendSms($mobile,$content);
    }

    /**
     * @param $template_key  模板关键字
     * @param $type          模板类型
     * @param $params        替换参数
     * @return mixed|string  模板内容
     * 读取消息模板内容
     */
    public static function getMessageTemplate($template_key , $type , $params = null){
        $condition = array();
        $condition[] = 'and';
        $condition[] = ['template_key' => $template_key];
        $condition[] = ['type' => $type];
        $query = SysMessageTemplate::find()->where($condition)->asArray()->one();

        if(!$query){
            return '';
        }

        $content = $query['content'];

        //处理替换参数内容，变量名与预先配置的一致。
        if($params){
            foreach($params as $key => $value){
                $content = str_replace($key, $value, $content);
            }
        }
        return $content;
    }
    
    /**
     * 判断数组中值是否存在
     * @param unknown $params   数组或对象
     * @param string $title     对应的键名
     * @return boolean
     */
    public static function arrayHasValue($params,$title = ''){
        if (is_array($params)){
            if (!isset($params[$title])){
                return false;
            }
        }elseif (!isset($params->$title)){
            return false;
        }
        return true;
    }

	/**
	 * @param 防止中文json转成uncode
	 */
	public static function  my_json_encode($arr){
		//convmap since 0x80 char codes so it takes all multibyte codes (above ASCII 127). So such characters are being "hidden" from normal json_encoding
        array_walk_recursive($arr, function (&$item, $key) {
			if (is_string($item)){
				$item = mb_encode_numericentity($item, array (0x80, 0xffff, 0, 0xffff), 'UTF-8'); }
			});
        return mb_decode_numericentity(json_encode($arr), array (0x80, 0xffff, 0, 0xffff), 'UTF-8');
	}

    /**
     * @param 获取客户端ip
     */
    public static function getClientIp(){
        if(getenv('HTTP_CLIENT_IP')) {
            $onlineip = getenv('HTTP_CLIENT_IP');
        } elseif(getenv('HTTP_X_FORWARDED_FOR')) {
            $onlineip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif(getenv('REMOTE_ADDR')) {
            $onlineip = getenv('REMOTE_ADDR');
        } else {
            $onlineip = $_SERVER['REMOTE_ADDR'];
        }
        return $onlineip;;
    }

    /**
     * @param 根据ip获取城市
     */
    public static function getIpLookup($ip = ''){
        if(empty($ip)){
            $ip = self::getClientIp();
        }
        $res = @file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=' . $ip);
        if(empty($res)){ return false; }
        $jsonMatches = array();
        preg_match('#\{.+?\}#', $res, $jsonMatches);
        if(!isset($jsonMatches[0])){ return false; }
        $json = json_decode($jsonMatches[0], true);
        if(isset($json['ret']) && $json['ret'] == 1){
            $json['ip'] = $ip;
            unset($json['ret']);
        }else{
            return false;
        }
        return $json;
    }
    
    /**
     * 
     * @param unknown $filed    第一行导出字段的标题            【必填】
     * @param unknown $params   导出数据                                    【必填】
     * @param unknown $filename 导出的excel文件名             【必填】
     * @param unknown $width    设置excel标题单元格宽度 【非必填】
     * 通过excel导出数据
     */
    public static function exportExcel($filed,$params,$filename,$width=[],$type=[]){
        $excel = new PHPExcel();
        $excel->setActiveSheetIndex(0);
        $filedKeys = array_keys($filed);
        $filedVals = array_values($filed);
        foreach ($filedVals as $key=>$value) {
            $cloumStr = chr(ord("A") + $key);
            $column = $cloumStr . "1";
            //设置标题
            $excel->getActiveSheet()->setCellValue($column, $value);
            //设置标题单元格宽度
            $width_val = self::arrayHasValue($width,$value) ? $width[$value] : 30;
            $excel->getActiveSheet()->getColumnDimension($cloumStr)->setWidth($width_val); 
        }
        
        foreach ($params as $data_key => $data_val) {
            $num = $data_key + 2;
            for ($j = 0; $j < count($filedKeys); $j++) {
                $cloumStr = chr(ord("A") + $j);
                $column = $cloumStr . $num;
                //在单元格内插入数据
                if(isset($data_val[$filedKeys[$j]])) {
                    if (count($type) > 0 && self::arrayHasValue($type,$filedKeys[$j])){
                        if ($type[$filedKeys[$j]] == 'setCellValueExplicit'){
                            $excel->getActiveSheet()->setCellValueExplicit($column, $data_val[$filedKeys[$j]]);
                        }
                    }else{
                        $excel->getActiveSheet()->setCellValue($column, $data_val[$filedKeys[$j]]);
                    }
                } else {
                    $excel->getActiveSheet()->setCellValue($column, '');
                }
            }
        }
        $excel->getActiveSheet()->setTitle('test-sheet');
        $objWriter = \PHPExcel_IOFactory::createWriter($excel, 'Excel5');
        if(php_sapi_name() != 'cli'){
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="'.$filename.'"');
            header('Cache-Control: max-age=0');
            $objWriter->save('php://output'); //文件通过浏览器下载
        }
    }
    
    /**
     * @return boolean|unknown  
     * 获取关键字
     */
    public static function getKeyword(){
        $redis_key = Yii::$app->params['sys_redis_prefix'].'goods_keyword';
        $key_word = Yii::$app->redis->get($redis_key);
        if (!$key_word){
            $key_word = GoodsKeyword::find()->select('name')->where('is_publish=1 and use_flg=1')->orderBy('sort asc')->asArray()->all();
            Yii::$app->redis->setex($redis_key,Yii::$app->params['frontend_session_timeout'],json_encode($key_word,JSON_UNESCAPED_UNICODE));
            $key_word = Yii::$app->redis->get($redis_key);
        }
        return json_decode($key_word,true);
    }
    
    /**
     * 获取可查看的推送商品的分类
     */
    public static function getPushGoodsRule(){
        $user_info = self::getloginUserInfo();
        $user_rule = (array)$user_info->user_rule;
        $goods_denre_type = $GLOBALS['_GOODS_GENRE_TYPE'];
        unset($goods_denre_type[0]);
        $goods_denre_key = array_keys($goods_denre_type);
        $user_rule_arr = [];
        $auth_rule = AuthRule::find()->select('param')->where(['in','id',$user_rule])->asArray()->all();
        $auth_rule = array_filter(array_column($auth_rule, 'param'));
        if (is_array($auth_rule) && count($auth_rule) > 0)foreach ($auth_rule as $rule_id){
            if (in_array(intval($rule_id), $goods_denre_key)){
                $user_rule_arr[] = intval($rule_id);
            }
        }
        return $user_rule_arr;
    }
    
    /**
     * 
     * @param unknown $user_id      员工id
     * @param unknown $is_admin     是否管理员   0：不是 1：是
     * 获取角色对应的权限
     */
    public static function getUserRule($user_id,$is_admin=0){
        $rule_id = UserMappedRole::find()->select('role_id')->where('user_id='.$user_id)->asArray()->one();
        $user_rule_arr = [];
        if (!$is_admin){
            if (self::arrayHasValue($rule_id,'role_id')){
                $user_rule = AuthAccess::find()->where(['in','role_id',explode(',', $rule_id['role_id'])])->asArray()->all();
                $rule_ids = is_array($user_rule) && count($user_rule) > 0 ? array_column($user_rule, 'rule_id') : [];
                
                if (is_array($rule_ids) && count($rule_ids) > 0)foreach ($rule_ids as $rule_id){
                    $user_rule_arr = array_merge($user_rule_arr,explode(',', $rule_id));
                }
            }
        }else{
            $user_rule = AuthRule::find()->select('id')->asArray()->all();
            $user_rule_arr = is_array($user_rule) && count($user_rule) > 0 ? array_column($user_rule, 'id') : [];
        }
        return $user_rule_arr;
    }
    
    /**
     *
     * @param unknown $service      $_SERVICE信息
     * @param unknown $call_url     生成二维码链接
     * @return string
     */
    public static function getWechatUrl($service,$call_url){
        $url = Yii::$app->params['wap'];
        if (self::arrayHasValue($service,'REDIRECT_URL')){
            $url .= $service['REDIRECT_URL'];
        }
        if (self::arrayHasValue($service,'REDIRECT_QUERY_STRING') && $service['REDIRECT_QUERY_STRING']){
            $url .= '?'.$service['REDIRECT_QUERY_STRING'];
            if (self::arrayHasValue($service,'share_key')){
                $url .= '&share_key='.$service['share_key'];
            }
        }else{
            if (self::arrayHasValue($service,'share_key')){
                $url .= '?share_key='.$service['share_key'];
            }
        }
        
        return $call_url.'?url='.$url;
    }

	/**
	 * @param 判断是否是手机浏览器
	 * @return bool
	 */
	public static function isMobile() {
		// 如果有HTTP_X_WAP_PROFILE则一定是移动设备
		if (isset($_SERVER['HTTP_X_WAP_PROFILE'])) {
			return true;
		}
		// 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
		if (isset($_SERVER['HTTP_VIA'])) {
			// 找不到为flase,否则为true
			return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
		}
		// 脑残法，判断手机发送的客户端标志,兼容性有待提高。其中'MicroMessenger'是电脑微信
		if (isset($_SERVER['HTTP_USER_AGENT'])) {
			$clientkeywords = array('nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips','panasonic','alcatel','lenovo','iphone','ipod','blackberry','meizu','android','netfront','symbian','ucweb','windowsce','palm','operamini','operamobi','openwave','nexusone','cldc','midp','wap','mobile','MicroMessenger');
			// 从HTTP_USER_AGENT中查找手机浏览器的关键字
			if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
				return true;
			}
		}
		// 协议法，因为有可能不准确，放到最后判断
		if (isset ($_SERVER['HTTP_ACCEPT'])) {
			// 如果只支持wml并且不支持html那一定是移动设备
			// 如果支持wml和html但是wml在html之前则是移动设备
			if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
				return true;
			}
		}
		return false;
	}

	/**
	 * @param 判断是否是微信浏览器
	 * @return bool
	 */
	public static function isWeixin() {
		if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
			return true;
		}
		return false;

	}


	/**
	 * @param $protocol 获取请求的url头协议
	 * @return string http:// 或者https://
	 */
	public static function getProtocol(){
		return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
		// $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
	}

	/**
	 * @param $para 对数组排序的数据 并且平成url链接
	 * @return mixed
	 */
	public static function genLinkstring($para)
	{
		ksort($para);
		reset($para);
		$arg  = "";
		while (list ($key, $val) = each ($para)) {
			$arg.=$key."=".$val."&";
		}
		//去掉最后一个&字符
		$arg = substr($arg,0,count($arg)-2);

		//如果存在转义字符，那么去掉转义
		if(get_magic_quotes_gpc()){
			$arg = stripslashes($arg);
		}

		return $arg;
	}


	/**
	 * 
	 * @param unknown $number  值的大小为10-100之间的整数值
	 * @return string
	 */
	public static function daxie($number){
	    if (strlen($number) == 2 && substr($number, 1) == '0'){
	        $number = substr($number, 0,1);
	    }
	    $number=str_split($number);
	    $arr=array('零','一','二','三','四','五','六','七','八','九');
	    $str = '';
	    if (count($number) > 0)foreach ($number as $number_val){
	        $number_val = intval($number_val);
	        $str .= $arr[$number_val];
	    }
	    return $str;
	}
	
	/**
	 *
	 * @param unknown $date  值的大小为0-7之间的整数值
	 * @return string
	 */
	public static function getWeek($date){
	    $number=str_split($date);
	    $arr=array('零','一','二','三','四','五','六','日');
	    $str = '星期';
	    if (count($number) > 0)foreach ($number as $number_val){
	        $number_val = intval($number_val);
	        $str .= $arr[$number_val];
	    }
	    return $str;
	}

	/**
	 * 
	 * @param unknown $sys_no int vip服务最新后缀
	 * @return unknown
	 * 获取vip服务code后缀
	 */
	public static function getSeqNo($sys_no){
	    $sys_no++;
	    $sts_no_len = strlen($sys_no);
	    $zero_len = 5-$sts_no_len;
	    $new_sys_no = '';
	    if ($zero_len > 0)for ($i=0;$i<$zero_len;$i++){
	        $new_sys_no .= '0';
	    }
	    $new_sys_no .= $sys_no;
	    return $new_sys_no;
	}

	//生成流水单号
	public static function getBillNo($fixe, $name, $len = 6)
    {
        $sys_seq = SysSeq::find()->where('name="' . $name . '"')->one();
        $seqno = $sys_seq->seq_no;
        $seqno++;
        $where = ['seq_no' => intval($seqno), 'edit_time' => date('Y-m-d H:i:s')];
        SysSeq::updateAll($where, 'name=:name', [':name' => $name]);

        $new_sys_no = '';
        $zero_len = $len - strlen($seqno);
        if ($zero_len > 0) {
            for ($i = 0; $i < $zero_len; $i++) {
                $new_sys_no .= '0';
            }
        }
        $new_sys_no .= $seqno;

        return $fixe . $new_sys_no;
    }

    /**
     *
     * @param $array 需要去重的数组
     * @param $un_key  依据的key
     * 二维数组根据某元素去重
     */
    public static function uniqueArray($array,$un_key){
        $result = array();
        foreach($array as $key=>$value){
            $has = false;
            foreach($result as $val){
                if($val[$un_key]==$value[$un_key]){
                    $has = true;
                    break;
                }
            }
            if(!$has){
                $result[]=$value;
            }
        }
        return $result;
    }
    
    /**
     * 生成随机字符串
     * @param number $length    生成的随机字符串的长度
     * @return string
     */
    public static function randStr($length = 6){
        //$str='1234567890';
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $code = '';
        for ( $i = 0; $i < $length; $i++ )
        {
            $code .= $chars[ mt_rand(0, strlen($chars) - 1) ];
        }
        return $code;
    }

	/**
	 * @param 登录返回来源页面
	 * @return mixed|null|string
	 */
	public static function loginReferrer(){
		$redirectUri	= Yii::$app->request->referrer;

		//当前页面的上个页面是空值 直接返回首页
		//if(!Yii::$app->request->referrer){
			//mod by FDG367 201801123 429 注册完毕直接是为登录状态，跳转至注册前一页 start
			//return Url::to('/site/index');
			if('login'==trim(Yii::$app->controller->id)){
				$redirectUri= Yii::$app->request->get('redirect_uri')? rawurldecode(Yii::$app->request->get('redirect_uri')) : $redirectUri;
			}else{
				$redirectUri= !empty(Yii::$app->request->referrer)? Yii::$app->request->referrer : Url::to('/site/index');
			}

			//mod by FDG367 20180111 429 注册完毕直接是为登录状态，跳转至注册前一页 end
		//}

		//如果是登录页面，密码重置，等相关的登录页面则返回首页
		if(preg_match('/\/login\/[\n\r\t]*?/',Yii::$app->request->referrer)){
			$redirectUri = Url::to('/site/index');
		}

		//add by FDG367 20180111 437 注册完毕直接是为登录状态，跳转至注册前一页 记录到redis start
		redisHelper::setWeChatRedirectUri($redirectUri);
		//add by FDG367 20180111 437 注册完毕直接是为登录状态，跳转至注册前一页 记录到redis end

		//返回上一个地址
		return $redirectUri;
	}

	/**
	 * @param 切换数据库驱动器
	 */
	public static function getDriverDb(){
		return Yii::$app->db;
	}

    //add by allen.qiang 20171124 增加视频URL输出 start
    /**随机取得视频URL
     * @return string
     */
    public static function getVideoUrl($type){
        $result =  rand(0,1);
        $videoFileName ='';
        if($type == 'pc'){
            $videoFileName = '856x480.mp4';
        }
        if($type == 'wap'){
            $videoFileName = '320x240.mp4';
        }
        switch($result){
            case 0:							//腾讯云服务器
                $videoUrl = 'http://111.231.72.225/public/video/' . $videoFileName;
                break;
            case 1:							//本地服务器
                $videoUrl = Yii::$app->params['imageBathUrl'] .'/static/pc/video/' . $videoFileName;
                break;
            default:
                $videoUrl = 'http://111.231.72.225/public/video/856x480.mp4';
                break;
        }
        return $videoUrl;
    }

    //add by allen.qiang 20171124 增加视频URL输出 end

    //删除导航缓存
    public static function delWebNavRedis(){
        $redis = new \common\helps\redisHelper();
        $redis->delFrontendNavMenu();
    }
    
    /**
     * @param unknown $params  where条件数据 一维数组
     * 返回数组
     */
    public static function mosaicWhere($params){
        if (count($params) == 0){
            return [];
        }
        $condition[] = 'and';
        //$param_key：需要进行搜索的字段和字段属性，通过||分割，例子：name||like ， $param_val搜索的值
        foreach ($params as $param_key=>$param_val){
            if ($param_val == ''){
                continue;
            }
            //$param_key_arr[0]为搜索的字段，$param_key_arr[1]为连接符号
            $param_key_arr = explode('|', $param_key);
            switch ($param_key_arr[1]){
                case 'eq':
                    $condition[] = [$param_key_arr[0]=>$param_val];
                    break;
                case 'like':
                    $condition[] = [$param_key_arr[1],$param_key_arr[0],$param_val];
                    break;
                case 'between':
                    $param_val_arr = explode(' - ', $param_val);
                    $condition[] = [$param_key_arr[1],$param_key_arr[0],$param_val_arr[0],$param_val_arr[1]];
                    break;
            }
        }
        return $condition;
    }

	/**
	 * @param add by FDG367 wap字体替换成rem 2018-01-22 start
	 * @param $str 要替换的字符串
	 * @return str
	 */
	public static function pregFilterReplace($str,$callBack='wapPregFilterReplaceCallback'){
		return preg_replace_callback(
			'/(\d+)px|width=\"(\d+)\"||height=\"(\d+)\"/U',
			array(new static(),$callBack),
			$str
		);
	}

	/**
	 * @param add by FDG367 PC字体替换成rem 回调函数 2018-01-22 start
	 * @param $str 要替换的字符串
	 * @return $str|null
	 */
	private static function pcPregFilterReplaceCallback($matches,$platform=2){
		switch(count($matches)){
			case 2://正常处理替换规则
				$returnStr = $matches[1]/20 .'rem';
				//$returnStr =  $matches[1]*$platform/40 .'rem';
				break;
			case 3://替换宽度规则 图片大于750 则宽度100% 小于750 则是百分比
				$returnStr = '';
				if(isset($matches[2])){
					if($matches[2]>=(375*$platform)){
						$returnStr = 'width=100%';
					}else{
						$returnStr = 'width='. $matches[2]/(375*$platform) *100 .'%';
					}
				}
				break;
			case 4://替换宽度规则
				$returnStr = '';
				break;
			default:
				$returnStr = null ;
				break;
		}

		return $returnStr;
	}

	/**
	 * @param add by FDG367 wap字体替换成rem 回调函数 2018-01-22 start
	 * @param $str 要替换的字符串
	 * @return $str|null
	 */
	private static function wapPregFilterReplaceCallback($matches){
		return self::pcPregFilterReplaceCallback($matches,2);
	}

	/**
	 * @param 二位数组根据某个键值排序
	 * @param $arr 	要排序的数据
	 * @param $keys 要排序的数据的键值
	 * @param $type 正序|倒叙
	 * @reutrn []
	 */
	public static function array_sort($arr, $keys, $type = SORT_DESC){
		$key_value = $new_array = array();
		foreach ($arr as $k => $v) {
			$key_value[$k] = $v[$keys];
		}
		if ($type == 'asc') {
			asort($key_value);
		} else {
			arsort($key_value);
		}
		reset($key_value);
		foreach ($key_value as $k => $v) {
			$new_array[$k] = $arr[$k];
		}
		return $new_array;
	}

	/**
	 * @param $list 分类数组（数据库直接查询的数组）note:暂时支持二级分类 如果增加三级分类或者四级分类则可以重构此方法为递归方法
	 * @param int $parent_id 级别字段
	 * @param int $pid
	 * @return array
	 */
	public static function getTree($list,$parent_id='parent_id',$pid = 0)
	{
		$tree = [];
		if (!empty($list)) {
			//先修改为以id为下标的列表
			$newList = [];
			foreach ($list as $k => $v) {
				$newList[$v['id']] = $v;
			}

			//根据分类的某个字段排序
			$newList=self::array_sort($newList,'sort');

			//然后开始组装成特殊格式
			foreach ($newList as $value) {
				if ($pid == $value[$parent_id]) {//先取出顶级
					$tree[] = &$newList[$value['id']];
				} elseif(isset($newList[$value[$parent_id]])) {//再判定非顶级的pid是否存在，如果存在，则再pid所在的数组下面加入一个字段items，来将本身存进去
					$newList[$value[$parent_id]]['childs'][] = &$newList[$value['id']];
				}
			}
		}
		return $tree;
	}

}
?>